package com.shelpe.services.sinbad.controller.sinbad;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.shelpe.services.sinbad.controller.dto.AutoProductDto;
import com.shelpe.services.sinbad.entity.jpa.AutoProductQueue;
import com.shelpe.services.sinbad.entity.jpa.Campaign;
import com.shelpe.services.sinbad.repository.jpa.AutoProductQueueRepository;
import com.shelpe.services.sinbad.repository.jpa.CampaignRepository;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping(value = "/sinbadservice/v2")
@Api("v2推广列表相关的API")
public class AutoQueueController {
	public final static Predicate[] TEMPLATE = new Predicate[0];

	@Autowired
	private AutoProductQueueRepository autoProductQueueRepository;
	@Autowired
	private CampaignRepository campaignRepository;

	/**
	 * 
	 * @description 计划页面知晓推广过程的列表
	 * @param campaignID
	 * @param timestamp
	 * @return
	 * @author yechen@shelpe.com
	 * @date 2018年3月15日上午10:06:49
	 */
	@ApiOperation(value = "推广过程状态列表的获取")
	@RequestMapping(method = RequestMethod.GET, path = "/campaigns/{campaign_id}/@queues_status")
	public List<AutoProductDto> findQueues(@PathVariable("campaign_id") long campaignID,
			@RequestParam(name = "timestamp", defaultValue = "0", required = false) long timestamp) {
		Campaign campaign = this.campaignRepository.findOne(campaignID);
		Assert.notNull(campaign, "该计划不存在");
		List<AutoProductQueue> pos = this.autoProductQueueRepository.findAll(new Specification<AutoProductQueue>() {
			@Override
			public Predicate toPredicate(Root<AutoProductQueue> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<Predicate>();
				predicates.add(cb.equal(root.get("campaignID"), campaignID));
				if (timestamp >= 0) {
					predicates.add(cb.notEqual(root.get("status"), AutoProductQueue.Status.success));
				}
				return cb.and(predicates.toArray(TEMPLATE));
			}

		});

		List<AutoProductDto> dtos = new ArrayList<AutoProductDto>();
		if (pos != null && pos.size() > 0) {
			for (AutoProductQueue queue : pos) {
				AutoProductDto dto = new AutoProductDto();
				dto.from(queue);
				dto.from(campaign);
				dtos.add(dto);
			}
		}
		return dtos;
	}

}
